// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  // 拷贝一下原始数据
  const _data = JSON.parse(JSON.stringify(event))
  // 保存修改结果
  const result = {}
  // 查找对应的书本
  const bookDb = cloud.database().collection('books').where({
    bookId: parseInt(_data.bookId)
  })
  const bookData = await bookDb.get()
  // 即将用于修改书本的数据
  const book = bookData.data[0]
  delete book._id
  book.comments[_data.index] = _data.comment
  // 执行书本数据修改
  result.result1 = await bookDb.update({
    data: book
  })

  // 查找对应评论
  const comment = cloud.database().collection('comments').where({
    commentId: parseInt(_data.comment.commentId)
  })
  result.result2 = await comment.update({
    data: _data.comment
  })

  const commentData = await comment.get()
  const _id = commentData.data[0].id

  // 查找对应用户
  const usersDb = cloud.database().collection('users')
  const userData = await usersDb.where({
    _id
  }).get()
  const user = userData.data[0]
  delete user._id
  user.comments.forEach(item => {
    if (item.commentId === parseInt(_data.comment.commentId)) {
      item.content = _data.comment.content
    }
  })
  result.result3 = await usersDb.where({
    _id
  }).update({
    data: user
  })
  return result
}
